package com.bjsxt.service.impl;

import com.alibaba.fastjson.JSON;
import com.bjsxt.feign.JwtToken;
import com.bjsxt.feign.OAuth2FeignClient;
import com.bjsxt.geetest.GeetestLib;
import com.bjsxt.model.GeetestForm;
import com.bjsxt.model.LoginForm;
import com.bjsxt.model.LoginUser;
import com.bjsxt.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;
    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private StringRedisTemplate strredisTemplate;

    @Override
    public LoginUser login(LoginForm loginForm) {
        log.info("用户{}登录",loginForm.getUsername());
        LoginUser loginUser = null;
        checkFormData(loginForm);
        //登录  用户名密码  换取 token  远程调用
       ResponseEntity<JwtToken> tokenResponseEntity =  oAuth2FeignClient.getToken("password",loginForm.getUsername(),loginForm.getPassword(),"member_type",basicToken);

       if(tokenResponseEntity.getStatusCode()== HttpStatus.OK){
           JwtToken jwtToken = tokenResponseEntity.getBody();
           log.info("调用成功，结果{}", JSON.toJSONString(jwtToken,true));
           loginUser = new LoginUser(loginForm.getUsername(),jwtToken.getExpires_in(),jwtToken.getToken_type()+" "+jwtToken.getAccess_token(),jwtToken.getRefresh_token());
           strredisTemplate.opsForValue().set(jwtToken.getAccess_token(),"",jwtToken.getExpires_in(), TimeUnit.SECONDS);
       }

        return loginUser;
    }

    private void checkFormData(LoginForm loginForm) {


        GeetestForm geetestForm = new GeetestForm();
        geetestForm.setGeetest_challenge(loginForm.getGeetest_challenge());
        geetestForm.setGeetest_seccode(loginForm.getGeetest_seccode());
        geetestForm.setGeetest_validate(loginForm.getGeetest_validate());
        geetestForm.check(geetestLib,redisTemplate);
    }
}
